package com.itmk.web.user_auth.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itmk.utils.ResultUtils;
import com.itmk.utils.ResultVo;
import com.itmk.web.user.entity.User;
import com.itmk.web.user_auth.entity.UserAuthParm;
import com.itmk.web.user.service.UserService;
import com.itmk.web.user_auth.entity.UserAuth;
import com.itmk.web.user_auth.server.UserAuthService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/api/UserAuth")
public class UserAuthController {
    @Autowired
    private UserService userService;

    @Autowired
    private UserAuthService userAuthService;

    @PostMapping("/auth")
    public ResultVo auth(@RequestBody UserAuth userAuth) {
        // 检查用户是否存在
        User user = userService.getById(userAuth.getUserId());
        if (user == null) {
            return ResultUtils.error("用户不存在");
        }

        // 检查是否已经认证过
        QueryWrapper<UserAuth> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserAuth::getUserId, userAuth.getUserId());
        UserAuth existingAuth = userAuthService.getOne(queryWrapper);
        if (existingAuth != null) {
            return ResultUtils.error("该用户已认证");
        }

        // 保存认证信息
        boolean saved = userAuthService.save(userAuth);
        return saved ? ResultUtils.success("认证成功") : ResultUtils.error("认证失败");
    }

    //    查询用户列表
    @GetMapping("/getList")
    public ResultVo getList(UserAuthParm userAuthParm) {
        QueryWrapper<UserAuth> queryWrapper = new QueryWrapper<>();
        // 使用Lambda表达式设置查询条件，如果e不为空，则按进行模糊查询
        queryWrapper.lambda().like(StringUtils.isNotEmpty(userAuthParm.getRealName()), UserAuth::getRealName, userAuthParm.getRealName());
// StringUtils.isNotEmpty(userAuthParm.getRealName()), // 条件判断
//        UserAuth::getRealName,                              // 实体类字段
//        userAuthParm.getRealName()                          // 搜索值
        IPage<UserAuth> page = new Page<>(userAuthParm.getCurrentPage(), userAuthParm.getPageSize());
        IPage<UserAuth> list = userAuthService.page(page, queryWrapper);
        return ResultUtils.success("get list success", list);
    }

    //    删除用户 ,通过id删除
    @DeleteMapping("/{userId}")
    public ResultVo del(@PathVariable("userId") int userId) {
        if (userAuthService.removeById(userId)) {
            return ResultUtils.success("delete success");
        } else {
            return ResultUtils.error("delete error");
        }
    }

}